package com.qian2.pricesharingapplication;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.lb2.JSONParser;
import com.example.pricesharingapplication.R;
import com.qian2.pricesharingapplication.EditProductActivity.GetProductDetails;
import com.qian2.pricesharingapplication.shoppinglist.ShoppingList;
import com.qian2.pricesharingapplication.shoppinglist.SqliteController;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ColorDrawable;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ProductPage extends Activity {

	TextView txtName;
	TextView txtCategory;
	TextView txtDesc;
	TextView txtBarcode;
	TextView txtBrand;
	ImageView picture;
	// Button btnSave;
	// Button btnDelete;

	String uid;
	String name;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();

	// single product url
	private static final String url_product_detials = "http://wwwfyp.cse.ust.hk:7117/get_product_details.php";

	// url to update product
	private static final String url_update_product = "http://wwwfyp.cse.ust.hk:7117/update_product.php";

	// url to delete product
	private static final String url_delete_product = "http://wwwfyp.cse.ust.hk:7117/delete_product.php";

	// url to get quotation list product
	private static final String url_quote_list = "http://wwwfyp.cse.ust.hk:7117/get_quote_list.php";

	ArrayList<HashMap<String, String>> quotationList;
	ListView listView;
	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_PRODUCT = "product";
	private static final String TAG_QUOTATION = "quotation";
	private static final String TAG_UID = "uid";
	private static final String TAG_NAME = "name";
	private static final String TAG_DATE = "date";
	private static final String TAG_SHOPNAME = "shopname";
	private static final String TAG_SHOPADDRESS = "shopAddress";
	private static final String TAG_QUANTITY = "quantity";
	private static final String TAG_PRICE = "price";
	private static final String TAG_REVIEW = "review";
	private static final String TAG_RATING = "rating";

	// private static final String TAG_CATEORY = "categoryName";
	private static final String TAG_DESCRIPTION = "description";
	private static final String TAG_Brand = "brand";
	private static final String TAG_Barcode = "upc";
	private static final String TAG_ParentName = "parentName";
	
	private ChooseAccount choose_acc;
	public static final String Email = "emailKey";

	// Check if there is a network connection
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_page);
		createPage();
		ActionBar bar = getActionBar();
		bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#77CEDA"))); 
		int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
		TextView yourTextView = (TextView)findViewById(titleId);
		yourTextView.setTextColor(Color.parseColor("#005d83"));
		getActionBar().setIcon(R.drawable.news_icon);
		// Button quotedButton = (Button) findViewById(R.id.);
		// B1.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View view) {
		// Intent i = getIntent();
		// String uid = i.getStringExtra(TAG_UID);
		//
		// // Starting new intent
		// Intent in = new Intent(getApplicationContext(),
		// EditProductActivity.class);
		// // sending uid to next activity
		// in.putExtra(TAG_UID, uid);
		//
		// // starting new activity and expecting some response back
		// startActivityForResult(in, 100);
		//
		// }});

		// Button B1=(Button) findViewById(R.id.EDITPRODUCT);
		// B1.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View view) {
		// Intent i = getIntent();
		// String uid = i.getStringExtra(TAG_UID);
		//
		// // Starting new intent
		// Intent in = new Intent(getApplicationContext(),
		// EditProductActivity.class);
		// // sending uid to next activity
		// in.putExtra(TAG_UID, uid);
		//
		// // starting new activity and expecting some response back
		// startActivityForResult(in, 100);
		//
		// }});

	}

	private void createPage() {
		quotationList = new ArrayList<HashMap<String, String>>();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		Intent i = getIntent();
		uid = i.getStringExtra(TAG_UID);
		// System.out.println("1:"+uid);
		Log.d("ProductPage : ", "i.getStringExtra(TAG_UID) =" + uid);
		new GetProductDetails().execute();
		loadImage("http://wwwfyp.cse.ust.hk:7117/Picture/upload/" + uid + "/"
				+ uid + ".jpg");

		listView = (ListView) findViewById(R.id.QuotationlistView);
		new GetQutationList().execute();

			
	}

	Bitmap bitmap;

	void loadImage(String image_location) {

		URL imageURL = null;

		try {
			imageURL = new URL(image_location);
		}

		catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			HttpURLConnection connection = (HttpURLConnection) imageURL
					.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream inputStream = connection.getInputStream();

			bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
			boolean filter = false;
			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			int screen_width = displaymetrics.widthPixels;
			int pic_witdth=bitmap.getWidth();
			int pic_height=bitmap.getHeight();
			int target_width= Integer.parseInt(Long.toString(Math.round(screen_width*0.25))); 
			int target_height=Integer.parseInt(Long.toString(Math.round(screen_width*0.25/pic_witdth*pic_height)));
			if (target_height>displaymetrics.heightPixels*0.15) target_height=Integer.parseInt(Long.toString(Math.round(displaymetrics.heightPixels*0.15)));
			bitmap=Bitmap.createScaledBitmap(bitmap, target_width,target_height, filter);													// bitmap
			ImageView image_view = (ImageView) findViewById(R.id.imageView1);
			image_view.setImageBitmap(bitmap);
			int target_scale=Integer.parseInt(Long.toString(Math.round(screen_width*0.25)));
			image_view.setMinimumHeight(target_scale);
			image_view.setMinimumWidth(target_scale);
			image_view.setBackgroundColor(Color.WHITE);
			image_view.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.parse("http://wwwfyp.cse.ust.hk:7117/Picture/upload/" + uid + "/"
							+ uid + ".jpg"), "image/*");
					startActivity(intent);
				}});
		} catch (IOException e) {
			ImageView image_view = (ImageView) findViewById(R.id.imageView1);
			image_view.setImageResource(R.drawable.ic_action_picture);
			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			int screen_width = displaymetrics.widthPixels;
			int target_scale=Integer.parseInt(Long.toString(Math.round(screen_width*0.25)));
			image_view.setMinimumHeight(target_scale);
			image_view.setMinimumWidth(target_scale);
		}
	}

	class GetProductDetails extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(ProductPage.this);
			pDialog.setMessage("Loading product details. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Getting product details in background thread
		 * 
		 * */
		ListAdapter adapter;
		@Override
		protected String doInBackground(String... params) {

			// updating UI from Background Thread
			runOnUiThread(new Runnable() {

				public void run() {
					// Check for success tag
					int success;
					try {
						// Building Parameters
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("uid", uid));
						// System.out.println("2:"+uid);
						// Log.d(getContentResolver().toString(), msg))
						// getting product details by making HTTP request
						// Note that product details url will use GET request

						// *******************************************
						// TODO (Edit product)gett data from database but not
						// from network
						if (!isOnline())
							return;
						JSONObject json = jsonParser.makeHttpRequest(
								url_product_detials, "GET", params);

						// check your log for json response
						System.out.println("Single Product Details"
								+ json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);
						if (success == 1) {
							// successfully received product details
							JSONArray productObj = json
									.getJSONArray(TAG_PRODUCT); // JSON Array

							// get first product object from JSON Array
							JSONObject product = productObj.getJSONObject(0);

							// product with this pid found
							// Edit Text

							txtName = (TextView) findViewById(R.id.name);
							txtCategory = (TextView) findViewById(R.id.categoryID);
							txtDesc = (TextView) findViewById(R.id.description);
							txtBarcode = (TextView) findViewById(R.id.barcode);
							txtBrand = (TextView) findViewById(R.id.brand);

							// display product data in EditText
							// System.out.println(product.getString(TAG_NAME));
							Log.d("product details: ", product.toString());
							name = product.getString(TAG_NAME);
							txtName.setText(product.getString(TAG_NAME));
							txtCategory.setText(product
									.getString(TAG_ParentName));
							txtDesc.setText(product.getString(TAG_DESCRIPTION));
							txtBarcode.setText(product.getString(TAG_Barcode));
							txtBrand.setText(product.getString(TAG_Brand));

						} else {
							// product with pid not found
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog once got all details
			
			CheckBox checkbox1=(CheckBox) findViewById(R.id.checkBox1);
			String name= ((TextView)findViewById(R.id.name)).getText().toString();
			SqliteController sqliteController= new SqliteController(ProductPage.this);
			if (sqliteController.check_item_exist(name)){
				checkbox1.setChecked(true);
				checkbox1.setText("Already added to shopping_list");
			} else {
				checkbox1.setChecked(false);
				checkbox1.setText("Add to shopping_list");
			}
			checkbox1.setOnCheckedChangeListener(new OnCheckedChangeListener(){

				@Override
				public void onCheckedChanged(CompoundButton buttonView,
						boolean isChecked) {
					// TODO Auto-generated method stub
					if (isChecked){
						buttonView.setText("Already added to shopping_list");
						SqliteController sqliteController= new SqliteController(ProductPage.this);
						HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
						String name= ((TextView)findViewById(R.id.name)).getText().toString();
						queryValues.put("ItemName", name);
						sqliteController.insertItem(queryValues);
//						if (((((MainActivity)ProductPage.this.getParent())))!=null)
//								((ShoppingList)(((MainActivity)ProductPage.this.getParent()).shopping_list_activity)).refresh();
					} else{
						buttonView.setText("Add to shopping_list");
						SqliteController sqliteController= new SqliteController(ProductPage.this);
						HashMap<String, Object> queryValues =  new  HashMap<String, Object>();
						String name= ((TextView)findViewById(R.id.name)).getText().toString();
						queryValues.put("ItemName", name);
						sqliteController.removeItem(name);
//						if (((((MainActivity)ProductPage.this.getParent())))!=null)
//							((ShoppingList)(((MainActivity)ProductPage.this.getParent()).shopping_list_activity)).refresh();
					}
				}});
		}
	}

	class GetQutationList extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		/**
		 * Getting Qutation List in background thread
		 * 
		 * */
		ListAdapter adapter;
		@Override
		protected String doInBackground(String... params) {

			// updating UI from Background Thread
			runOnUiThread(new Runnable() {

				public void run() {
					// Check for success tag
					int success;
					try {
						// Building Parameters
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("uid", uid));

						if (!isOnline())
							return;
						JSONObject json = jsonParser.makeHttpRequest(
								url_quote_list, "GET", params);

						// check your log for json response
						System.out
								.println("Quotation List: " + json.toString());

						// json success tag
						success = json.getInt(TAG_SUCCESS);
						if (success == 1) {
							// successfully received product details
							JSONArray quotationObj = json
									.getJSONArray(TAG_QUOTATION); // JSON Array

							// get first product object from JSON Array

							quotationList.clear();
							for (int i = 0; i < quotationObj.length(); i++) {
								JSONObject c = quotationObj.getJSONObject(i);
								// adding each child node to HashMap key =>
								// value

								// creating new HashMap
								HashMap<String, String> map1 = new HashMap<String, String>();

								// adding each child node to HashMap key =>
								// value

								map1.put(TAG_DATE, c.getString(TAG_DATE).substring(0,10));
								map1.put(TAG_SHOPNAME,
										c.getString(TAG_SHOPNAME));
								map1.put(TAG_SHOPADDRESS,
										c.getString(TAG_SHOPADDRESS));
								map1.put(TAG_QUANTITY,
										c.getString(TAG_QUANTITY));

								map1.put(TAG_PRICE, c.getString(TAG_PRICE));
								map1.put(TAG_REVIEW, c.getString(TAG_REVIEW));
								map1.put(TAG_RATING, c.getString(TAG_RATING));

								// adding HashList to ArrayList
								quotationList.add(map1);
							}

						} else {
							// product with pid not found
						}

					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			});

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			System.out.println("ProductPage.GetQutationList.onPostExecute()");
			ListAdapter adapter = new SimpleAdapter(ProductPage.this,
					quotationList, R.layout.activity_quotation_list,
					new String[] { TAG_DATE, TAG_PRICE, TAG_RATING,
							TAG_SHOPNAME, TAG_SHOPADDRESS, TAG_REVIEW },
					new int[] { R.id.listdate, R.id.listprice, R.id.listrating,
							R.id.listshopname, R.id.listshopaddress,
							R.id.listreview });
			// updating listview
			listView.setAdapter(adapter);
			pDialog.dismiss();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is
		// present.x
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.product_page, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public void startQuote(){
		Intent in = new Intent(getApplicationContext(),
				QuotationActivity.class);
		// sending upc to next activity
		in.putExtra(TAG_UID, uid);
		in.putExtra(TAG_NAME, name);
		startActivityForResult(in, 100);
		
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.action_quote:
			if(!MainActivity.sharedpreferences.contains(Email)){
				Intent in2 = new Intent(getApplicationContext(),
						ChooseAccount.class);
				startActivityForResult(in2, 90);
				
			}
			else{
				startQuote();
			}
			
//			Intent in = new Intent(getApplicationContext(),
//					QuotationActivity.class);
//			// sending upc to next activity
//			in.putExtra(TAG_UID, uid);
//			in.putExtra(TAG_NAME, name);
//			startActivityForResult(in, 100);
			return true;
		case R.id.action_settings:
			// TODO Add settings
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		System.out.println("resultcode: "+resultCode );
		
		
		if(resultCode == RESULT_OK){
			//createPage();
			System.out.println("ProductPage.onActivityResult(): result ok ");
			new GetQutationList().execute();
		}else if (resultCode == RESULT_CANCELED) {
			System.out.println("ProductPage.onActivityResult(): result cancel ");
			new GetQutationList().execute();
			Toast toast = Toast.makeText(this, "Result Cancel", 0);
			toast.show();
		}else if(requestCode==90){
			startQuote();
		}
		else {
			System.out.println("ProductPage.onActivityResult() result:" + resultCode);

		}
	}


	

}
